<template>
  <div class="app-container home">
    <ContentWrap>
      <CustomBox>
        <div style="font-size: 20px;color: #333;margin-bottom: 10px;display: flex;align-items: center;">
          <div style="width: 4px;height: 22px;background-color: #ed368a;margin-right: 5px;"></div>
          <span>{{ $store.getters.deptName }}</span>
          <span style="color: #ed368a;padding: 0 5px;">{{ moment().subtract(1, 'month').format('MM') }}</span>
          <span>月看板</span>
        </div>

        <el-row :gutter="5">
          <el-col :span="3" v-for="item in overviewDataList">
            <div class="box1">
              <div v-if="item.rate!==''" class="top">
                <div>
                  <span class="value">{{ item.value }}</span><span style="font-size: 14px;">{{ item.unit }}</span>
                </div>
              </div>
              <div v-else class="top">
                <div>
                  <span class="value">{{ item.value }}</span>
                  <span v-if="item.unit !==''" class="unit">&nbsp;&nbsp;{{ item.unit }}</span>
                </div>
              </div>

              <div class="bottom" v-if="item.rate">
                <div>
                  {{ item.text }}
                </div>
                <div v-if="item.rate">
                  <span class="rate">{{ item.rate }}%</span>
                  <img v-if="item.rate !== ''" width="16" height="16" style="margin-left: 3px;"
                       :src="require(`@/assets/leakage/` + (item.increased === 1?'up_y':'down_g') + '.svg')"
                       alt=""/>
                </div>
              </div>

              <div class="bottom" v-else style="justify-content: center !important;">
                {{ item.text }}
              </div>
            </div>
          </el-col>
        </el-row>

        <hr style="margin: 5px;width: 49.5%;"/>

        <el-row :gutter="10" style="margin-top: 10px;">
          <el-col :span="12">
            <div style="display: flex;justify-content: space-between;">
              <div style="width: 14%;height: 102px;cursor: pointer;text-align: center;padding: 2px 0;"
                   :style="{border: selectedDfq===undefined?'2px solid #1890ff':'1px solid #E3E3E3'}"
                   @click="handleDfqSelected(undefined,true)">
                <div style="font-size: 20px;font-weight: bold;color: #1890ff;">公司</div>
                <img :src="require(`@/assets/leakage/company.png`)"
                     style="transform: scaleX(1.4) scaleY(1.25);margin-top: 10px;" alt="">
              </div>

              <div style="width: 85%;height: 110px;">
                <swiper class="swiper" :options="swiperOption">
                  <swiper-slide v-for="item in dfqKpiData">
                    <div
                      style="width: 225px;height: 100px;cursor: pointer;text-align: center;border: 1px solid #E3E3E3;"
                      :style="{border: selectedDfq !== undefined && selectedDfq.id === item.id?'1px solid #1890ff':'1px solid #E3E3E3'}"
                      @click="handleDfqSelected(item,false)" @dblclick="handleDetailClick(item)">
                      <div
                        style="height: 30%;font-size: 16px;border-bottom: 1px solid #E3E3E3;padding: 6px 10px;display: flex;align-items: center;justify-content: center;"
                        :style="{backgroundColor: selectedDfq !== undefined && selectedDfq.id === item.id?'#1890ff':'#FFFFFF',
                                color: selectedDfq !== undefined && selectedDfq.id === item.id?'#FFFFFF':'#333'}">
                        <span style="font-weight: bold;">{{ item.name }}</span>
                        <img width="18" height="18" style="cursor: pointer;margin-left: 5px;"
                             :src="require(`@/assets/leakage/` + (selectedDfq !== undefined && selectedDfq.id === item.id?'baisedingwei':'dingwei') + '.svg')"
                             alt="" @click="handleLocatorClick(item)"/>
                      </div>
                      <div style="height: 70%;padding: 10px;">
                        <el-row :gutter="5"
                                style="font-size: 16px;display: flex;justify-content:right;align-items: center;">
                          <el-col :span="10" style="text-align: right;"><span>供水量：</span></el-col>
                          <el-col :span="14" style="text-align: center;"><span>{{ item.supply }} m³</span></el-col>
                        </el-row>
                        <el-row :gutter="5" style="font-size: 16px;display: flex;align-items: center;">
                          <el-col :span="10" style="text-align: right;"><span>产销差率：</span></el-col>
                          <el-col :span="14" style="text-align: center;"><span>{{ item.rate }} %</span></el-col>
                        </el-row>
                      </div>
                    </div>
                  </swiper-slide>
                  <div class="swiper-button-prev" slot="button-prev"></div>
                  <div class="swiper-button-next" slot="button-next" style="margin-right: 8px;"></div>
                </swiper>
              </div>
            </div>

            <hr style="margin: 0;"/>

            <div style="margin-top: 10px;">
              <div style="display: flex;width: 100%;">
                <div style="width: 70%;">
                  <div style="display: flex;align-items: center;">
                    <div style="width: 4px;height: 22px;background-color: #ed368a;margin-right: 5px;"></div>
                    <div style="font-size: 18px;color: #333;">分区供水量趋势</div>
                  </div>
                  <div id="index-overview-chart" style="width: 100%;height: 230px;margin-top: 10px;"></div>
                </div>

                <div style="width: calc(30% - 10px);height: 270px;margin-left:10px;">
                  <div style="display: flex;align-items: center;">
                    <div style="width: 4px;height: 22px;background-color: #ed368a;margin-right: 5px;"></div>
                    <div style="font-size: 18px;color: #333;">分区占比</div>
                  </div>
                  <div v-for="item in dfqProportionData" :style="{marginTop: item.top + 'px'}">
                    <div style="display: flex;justify-content: space-between;align-items: end;margin-bottom: 5px;">
                      <div style="font-size: 16px;">
                        <div>{{ item.text }}</div>
                        <div style="margin-top: 5px;">{{ item.value }} m³</div>
                      </div>
                      <div style="font-size: 24px;">{{ item.proportion }} %</div>
                    </div>
                    <el-progress :percentage="item.proportion" :show-text="false"></el-progress>
                  </div>
                </div>
              </div>
            </div>

            <hr style="margin: 0;"/>

            <div style="margin-top: 10px;">
              <div style="margin: 10px 0;display: flex;justify-content: space-between;align-items: end">
                <div style="display: flex;align-items: center;">
                  <div style="width: 4px;height: 22px;background-color: #ed368a;margin-right: 5px;"></div>
                  <div style="font-size: 18px;color: #333;">DMA绩效排行</div>
                </div>
                <div style="display: flex;">
                  <div v-for="item in dmaKpiStatistic" style="display: flex;margin-left: 10px;">
                    <div :style="{width: '30px', height: '18px', borderRadius: '4px', backgroundColor: item.color}"
                         :title="item.tips"></div>
                    <div style="margin-left: 5px;">{{ item.count }}个</div>
                  </div>
                </div>
              </div>

              <el-table :data="dmaKpiData" border size="mini" :height="getTableHeight" style="width: 100%">
                <el-table-column type="index" width="35" label="#"></el-table-column>
                <el-table-column prop="name" label="DMA"></el-table-column>
                <el-table-column prop="locator" label="定位" align="center" width="60">
                  <template slot-scope="scope">
                    <i class="el-icon-map-location" style="color: #00afff;font-size: 16px;cursor: pointer;"
                       @click="handleLocatorClick(scope.row)"></i>
                  </template>
                </el-table-column>
                <el-table-column prop="supply" label="供水量(m³)" align="center" width="120" sortable></el-table-column>
                <el-table-column prop="sale" label="售水量(m³)" align="center" width="120" sortable></el-table-column>
                <el-table-column prop="free" label="无收益水量(m³)" align="center" width="140"
                                 sortable></el-table-column>
                <el-table-column prop="rate" label="产销差率(%)" align="center" width="120" sortable>
                  <template slot-scope="scope">
                    <el-tag :color="getKpiRateColor(scope.row.rate)">
                      <span style="color: #FFFFFF;">{{ scope.row.rate }}</span>
                    </el-tag>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-col>

          <el-col :span="12">
            <div>
              <div style="width: 100%;" :style="getMapHeight">
                <L7Map @mapLoaded="handleMapLoaded" :zoom="getMapZoom">
                  <div
                    style="position: absolute;top: 0;left: 5px;z-index: 1000;margin: 5px;padding: 5px;background-color: #FFFFFF;border: 1px solid #7cbfee;">
                    计量分区
                    <el-switch style="margin-right: 8px;"
                               v-model="polygonLayersVisible"
                               active-color="#13ce66"
                               inactive-color="#ff4949" @change="handlePolygonLayersVisibleChange">
                    </el-switch>
                    供水管网
                    <el-switch style="margin-right: 8px;"
                               v-model="pipeNetworkVisible"
                               active-color="#13ce66"
                               inactive-color="#ff4949" @change="handlePipeNetworkVisibleChange">
                    </el-switch>
                    考核表
                    <el-switch style="margin-right: 8px;"
                               v-model="examineTerminalMarkerVisible"
                               active-color="#13ce66"
                               inactive-color="#ff4949" @change="handleExamineTerminalMarkerVisibleChange">
                    </el-switch>
                    大用户
                    <el-switch style="margin-right: 8px;"
                               v-model="dyhTerminalMarkerVisible"
                               active-color="#13ce66"
                               inactive-color="#ff4949" @change="handleDyhTerminalMarkerVisibleChange">
                    </el-switch>
                  </div>
                </L7Map>
                <div style="position: absolute;bottom: 0;right: 5px;">
                  <img :src="require(`@/assets/leakage/bi/legend.png`)" width="180" height="32" alt="">
                </div>
              </div>
            </div>
          </el-col>
        </el-row>
      </CustomBox>
    </ContentWrap>
  </div>
</template>

<script>
import L7Map from "@/components/L7Maps/map.vue";
import {PolygonLayer, Marker, Popup, LineLayer, MarkerLayer, Zoom, PointLayer} from '@antv/l7';
import * as echarts from "echarts";
import 'swiper/css/swiper.css'
import {Swiper, SwiperSlide} from 'vue-awesome-swiper'
import {getOverviewData, getDfqKpiData, getDMAKpiData} from '@/api/leakage/biZbx'
import * as turf from "@turf/turf";
import {drawWmsLayer} from '@/components/L7Maps/util'
import {listAllTerminals} from "@/api/leakage/terminalsInfo";
import {getZoneJoinTerminals} from "@/api/leakage/zoneJoin";
import moment from "moment";
import {listGisLine} from "@/api/leakage/gisLine";
import {listGisLayer} from "@/api/leakage/gisLayer";
import {listGisPoint} from "@/api/leakage/gisPoint";
import {getGisLayers} from "@/utils/wfsUtil";

require('echarts/theme/macarons') // echarts theme

const colors = ['#3488fa', '#42d4ad', '#f0589d'];

const sumByKey = (arr, key) => {
  return arr.reduce((prev, cur) => {
    return parseFloat(prev) + parseFloat(cur[key])
  }, 0.00)
}

export default {
  name: "Index",
  components: {L7Map, Swiper, SwiperSlide},
  data() {
    return {
      screenHeight: null,
      mapScene: undefined,
      mapZoom: undefined,
      mapCenter: undefined,
      // 考核表图层
      examineTerminalMarkerLayer: undefined,
      // 考核表图层是否可见
      examineTerminalMarkerVisible: false,
      // 大用户图层
      dyhTerminalMarkerLayer: undefined,
      // 大用户表图层是否可见
      dyhTerminalMarkerVisible: false,
      // 管线图层
      pipeNetworkLayers: [],
      // 地图管点图层列表
      mapPointLayerList: [],
      // 地图管线图层列表
      mapLineLayerList: [],
      // 管线图层是否可见
      pipeNetworkVisible: true,
      // 面图层
      polygonLayers: [],
      polygonLayersVisible: true,
      currentClickLayers: [],
      // 终端表数据
      terminalDataList: [],
      layerOriginColorMap: {},
      overviewDataList: [
        {text: '供水总量', key: 'supply', value: 0, unit: 'm³', rate: '', increased: 0},
        {text: '售水量', key: 'sale', value: 0, unit: 'm³', rate: '', increased: 0},
        {text: '无收益水量', key: 'free', value: 0, unit: 'm³', rate: '', increased: 0},
        {text: '产销差率', key: 'cxcl', value: 0, unit: '%', rate: '', increased: 0},
        {text: '大用户用水量', key: 'dyhYsl', value: 0, unit: 'm³', rate: '', increased: 0},
        {text: 'DMA数', key: 'dma', value: 0, unit: '', rate: '', increased: 0},
        {text: '大用户数', key: 'dyh', value: 0, unit: '', rate: '', increased: 0},
        {text: '户表数', key: 'meter', value: 0, unit: '', rate: '', increased: 0},
      ],
      selectedDfq: undefined,
      companyKpiData: undefined,
      companyAllKpiData: undefined,
      dfqZoneData: [],
      dfqKpiData: [],
      dfqAnnualKpiData: [],
      dfqGroupKpiData: [],
      dfqProportionData: [
        {text: '供水量', value: 0, proportion: 0, top: 10},
        {text: '售水量', value: 0, proportion: 0, top: 24},
        {text: '无收益水量', value: 0, proportion: 0, top: 24},
      ],
      dmaZoneData: [],
      dmaKpiData: [],
      dmaKpiStatistic: [
        {color: '#3cdf73', count: 0, tips: '产销差率 < 10%'},
        {color: '#ffd400', count: 0, value: 10, tips: '10% <= 产销差率 < 20%'},
        {color: '#ff9900', count: 0, value: 20, tips: '20% <= 产销差率 < 30%'},
        {color: '#e9605d', count: 0, value: 30, tips: '产销差率 >= 30%'},
      ],
      overviewChart: undefined,
      baseOption: {
        color: colors,
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross'
          }
        },
        grid: {
          top: '15%',
          right: '8%',
          bottom: '8%',
          left: '15%',
          containsLabel: true
        },
        legend: {
          data: ['供水量(m³)', '售水量(m³)', '产销差率(%)']
        },
        xAxis: {
          type: 'category',
          data: []
        },
        yAxis: [
          {
            type: 'value',
            alignTicks: true,
            axisLine: {
              show: true,
              lineStyle: {
                color: colors[0]
              }
            },
            axisLabel: {
              formatter: '{value} m³'
            }
          },
          {
            type: 'value',
            position: 'right',
            alignTicks: true,
            axisLine: {
              show: true,
              lineStyle: {
                color: colors[2]
              }
            },
            axisLabel: {
              formatter: '{value} %'
            }
          },
        ],
        series: [
          {
            name: '供水量(m³)',
            type: 'bar',
            data: []
          },
          {
            name: '售水量(m³)',
            type: 'bar',
            data: []
          },
          {
            name: '产销差率(%)',
            type: 'line',
            yAxisIndex: 1,
            data: []
          }
        ]
      },
      swiperOption: {
        slidesPerView: 3,
        spaceBetween: 0,
        slidesPerGroup: 3,
        loop: false,
        loopFillGroupWithBlank: false,
        pagination: {
          el: '.swiper-pagination',
          clickable: true
        },
        navigation: {
          nextEl: '.swiper-button-next',
          prevEl: '.swiper-button-prev'
        }
      },
    }
  },
  methods: {
    handleMapLoaded(scene) {
      this.mapScene = scene
      this.mapZoom = scene.getZoom()
      this.mapCenter = scene.getCenter()
      this.examineTerminalMarkerLayer = new MarkerLayer();
      this.dyhTerminalMarkerLayer = new MarkerLayer();
      this.pipeNetworkLayers = []

      const zoom = new Zoom({
        zoomInTitle: '放大',
        zoomOutTitle: '缩小',
        position: 'bottomleft'
      });
      this.mapScene.addControl(zoom);
      this.mapScene.addImage('famen', '/images/gis-svg/GIS-TL_famen.png');
      this.mapScene.addImage('shuichang', '/images/gis-svg/GIS-TL_shuichang.png');
      this.mapScene.addImage('xiaofangshuan', '/images/gis-svg/GIS-TL_xiaoquxiaohuoshuan.svg');
      this.mapScene.addImage('lianjiedian', '/images/gis-svg/GIS-TL_linkpoint.png');

      // this.drawPipeNetwork()
      getGisLayers(scene, this.pipeNetworkLayers)
    },
    handlePipeNetworkVisibleChange(val) {
      if (val) {
        this.mapPointLayerList.forEach(layer => {
          layer.show()
        })
        this.mapLineLayerList.forEach(layer => {
          layer.show()
        })
        this.pipeNetworkLayers.forEach(layer => {
          layer.show()
        })
      } else {
        this.mapPointLayerList.forEach(layer => {
          layer.hide()
        })
        this.mapLineLayerList.forEach(layer => {
          layer.hide()
        })
        this.pipeNetworkLayers.forEach(layer => {
          layer.hide()
        })
      }
    },
    handleExamineTerminalMarkerVisibleChange(val) {
      if (val) {
        this.addTerminalMarkerToMap()
      } else {
        this.examineTerminalMarkerLayer.clear()
      }
    },
    handleDyhTerminalMarkerVisibleChange(val) {
      if (val) {
        this.addTerminalMarkerToMap()
      } else {
        this.dyhTerminalMarkerLayer.clear()
      }
    },
    handlePolygonLayersVisibleChange(val) {
      if (val) {
        this.polygonLayers.forEach(layer => {
          layer.show()
        })
      } else {
        this.polygonLayers.forEach(layer => {
          layer.hide()
        })
      }
    },
    initChart() {
      this.overviewChart = echarts.init(document.getElementById('index-overview-chart'), 'macarons')
      this.overviewChart.setOption(this.baseOption)
    },
    loadMonitorTerminals() {
      getZoneJoinTerminals({terminalMark: 1}).then((res => {
        this.terminalDataList = res.rows
      }))
    },
    loadOverviewData() {
      getOverviewData({}).then(res => {
        const data = res.data
        this.overviewDataList.forEach(item => {
          item.value = data[item.key]
          const hbValue = data[item.key + 'Hb']
          if (hbValue !== undefined) {
            item.rate = hbValue
            item.increased = parseFloat(hbValue) > 0 ? 1 : 0
          }
        })
      })
    },
    loadDfqKpiData() {
      getDfqKpiData({}).then(res => {
        const {company, company_all, all, group, dfq, kpi} = res.data
        const data = []

        kpi.forEach(item => {
          const dfqZone = dfq.filter(d => d.areaID === item.zbz1)
          const dfqInfo = dfqZone[0]
          data.push({
            id: dfqInfo.areaID,
            name: dfqInfo.areaName,
            areaPoint: dfqInfo.areaPoint,
            month: item.zbz3,
            supply: item.zbz4,
            sale: item.zbz5,
            free: item.zbz6,
            rate: item.zbz7,
            zoom: dfqInfo.zoom
          })
        })

        this.companyKpiData = company
        this.companyAllKpiData = company_all
        this.dfqZoneData = dfq
        this.dfqKpiData = data
        this.dfqAnnualKpiData = all
        this.dfqGroupKpiData = group

        this.makeChartData()
        this.makeProportionData()
        setTimeout(() => {
          this.drawDfqToMap()
        }, 1000)
      })
    },
    loadDMAKpiData() {
      const query = {}
      if (this.selectedDfq !== undefined) {
        query.zbz2 = this.selectedDfq.id
      }
      getDMAKpiData(query).then(res => {
        const {dma, kpi} = res.data
        const data = []

        if (kpi.length > 0) {
          kpi.forEach(item => {
            const dmaZone = dma.filter(d => d.areaID === item.zbz1)
            const dmaInfo = dmaZone[0]
            data.push({
              id: dmaInfo.areaID,
              levelType: dmaInfo.levelType,
              name: dmaInfo.areaName,
              areaPoint: dmaInfo.areaPoint,
              month: item.zbz3,
              supply: item.zbz4,
              sale: item.zbz5,
              free: item.zbz6,
              rate: item.zbz7,
              zoom: dmaInfo.zoom
            })
          })

          this.dmaZoneData = dma
          this.dmaKpiData = data
          this.dmaKpiData.sort((a, b) => a.rate - b.rate > 0 ? -1 : 1)
          this.dmaKpiStatistic[0].count = data.filter(item => parseFloat(item.rate) < 10).length
          this.dmaKpiStatistic[1].count = data.filter(item => parseFloat(item.rate) >= 10 && parseFloat(item.rate) < 20).length
          this.dmaKpiStatistic[2].count = data.filter(item => parseFloat(item.rate) >= 20 && parseFloat(item.rate) < 30).length
          this.dmaKpiStatistic[3].count = data.filter(item => parseFloat(item.rate) >= 30).length

          setTimeout(() => {
            this.drawDmaToMap()
          }, 1200)
        }
      })
    },
    getKpiRateColor(rate) {
      const colors = this.dmaKpiStatistic.map(item => item.color)
      const fRate = parseFloat(rate)
      if (fRate < 10) {
        return colors[0]
      } else if (fRate <= 10 && fRate < 20) {
        return colors[1]
      } else if (fRate <= 20 && fRate < 30) {
        return colors[2]
      } else {
        return colors[3]
      }
    },
    makeChartData() {
      const option = Object.assign({}, this.baseOption)

      if (this.selectedDfq) {
        const data = this.dfqAnnualKpiData.filter(item => item.zbz1 === this.selectedDfq.id)
        const xAxisData = data.map(item => item.zbz3)
        xAxisData.sort()
        const series1 = data.map(item => item.zbz4)
        const series2 = data.map(item => item.zbz5)
        const series3 = data.map(item => item.zbz7)
        option.xAxis.data = xAxisData
        option.series[0].data = series1
        option.series[1].data = series2
        option.series[2].data = series3
      } else {
        const xAxisData = Object.keys(this.dfqGroupKpiData)
        option.xAxis.data = xAxisData
        xAxisData.sort()
        const series1 = [], series2 = [], series3 = []
        this.companyAllKpiData.forEach(m => {
          const supply = m.zbz1
          series1.push(supply)
          const sale = m.zbz2
          series2.push(sale)
          const rate = m.zbz4
          series3.push(rate)
        })
        option.series[0].data = series1
        option.series[1].data = series2
        option.series[2].data = series3
      }

      this.overviewChart.setOption(option)
    },
    makeProportionData() {
      if (Object.keys(this.dfqGroupKpiData).length) {
        const supplyData = this.dfqProportionData[0]
        const saleData = this.dfqProportionData[1]
        const freeData = this.dfqProportionData[2]

        if (this.selectedDfq) {
          const dfqKpiList = this.dfqKpiData.filter(item => item.id === this.selectedDfq.id)
          if (dfqKpiList !== undefined && dfqKpiList.length) {
            const dfqKpi = dfqKpiList[0]

            const dataList = this.dfqGroupKpiData[dfqKpi.month]
            const supplySum = this.companyKpiData.zbz1
            const saleSum = this.companyKpiData.zbz2
            const freeSum = this.companyKpiData.zbz3

            supplyData.value = dfqKpi.supply
            supplyData.proportion = supplySum === 0 ? 0 : parseFloat((dfqKpi.supply / supplySum * 100.0).toFixed(2))
            saleData.value = dfqKpi.sale
            saleData.proportion = saleSum === 0 ? 0 : parseFloat((dfqKpi.sale / saleSum * 100.0).toFixed(2))
            freeData.value = dfqKpi.free
            freeData.proportion = freeSum === 0 ? 0 : parseFloat((dfqKpi.free / freeSum * 100.0).toFixed(2))
          }
        } else {
          supplyData.value = this.companyKpiData.zbz1
          supplyData.proportion = 100
          saleData.value = this.companyKpiData.zbz2
          saleData.proportion = 100
          freeData.value = this.companyKpiData.zbz3
          freeData.proportion = 100
        }
      }
    },
    handleDfqSelected(item, isRoot) {
      this.selectedDfq = item
      this.makeProportionData()
      this.loadDMAKpiData()
      this.makeChartData()
      if (isRoot) {
        if (this.currentClickLayers.length) {
          this.currentClickLayers.forEach(layer => {
            this.mapScene.removeLayer(layer)
          })
          this.currentClickLayers = []
          this.mapScene.setZoomAndCenter(this.mapZoom, this.mapCenter)
        }
        this.resetLineLayerColorAndSize()
      }
    },
    handleLocatorClick(item) {
      const coordinates = []
      coordinates.push(JSON.parse(item.areaPoint))
      const layerName = (item.levelType === '2' ? 'polygon-dma-' : 'polygon-dfq-') + item.id
      const layer = this.mapScene.getLayerByName(layerName)
      this.handlePolygonLayerClick(this.mapScene, coordinates, item.id, item.name, item.rate, item.zoom, layer.coordCenter, item.levelType === '2')
    },
    handleDetailClick(item) {
      // 本页面打开
      this.$router.push({path: '/analysis/dfq', query: {id: item.id}})
    },
    addTerminalMarkerToMap() {
      const that = this
      const terminals = this.terminalDataList.filter(item => item.lat != null && item.lng != null)
      let point
      if (this.examineTerminalMarkerLayer) {
        this.examineTerminalMarkerLayer.clear()
      }
      if (this.dyhTerminalMarkerLayer) {
        this.dyhTerminalMarkerLayer.clear()
      }
      terminals.forEach(t => {
        point = [parseFloat(t.lng), parseFloat(t.lat)]

        const markerIcon = t.hookType === 1 ? `/images/terminal.png` : `/images/senior.png`
        const markerContent = `<div><img src="${markerIcon}" style="width: 40px;height: 40px;"></div>`
        let el = document.createElement('div')
        el.innerHTML = markerContent
        const marker = new Marker({element: el, draggable: false, offsets: [0, 0]}).setLnglat({
          lng: parseFloat(t.lng),
          lat: parseFloat(t.lat)
        })

        const data = t.realtimeGatherData
        const popup = new Popup({
          title: t.terminalName,
          lngLat: {
            lng: parseFloat(t.lng),
            lat: parseFloat(t.lat)
          },
          offsets: [0, 40],
          closeButton: false,
          html: `<div>
                  <div>瞬时流量：${data && data.instantNumber != null ? '<span style="color: limegreen;">' + data.instantNumber + '</span> m³/h' : '<span style="color: red;">-<span>'}</div>
                  <div>累计流量：${data && data.totalFlow != null ? '<span style="color: limegreen;">' + data.totalFlow + '</span> m³' : '<span style="color: red;">-<span>'}</div>
                  <div>压&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;力：${data && data.pressure != null ? '<span style="color: limegreen;">' + data.pressure + '</span> MPa' : '<span style="color: red;">-<span>'}</div>
                  <div>信号强度：${data && data.terminalCSQ != null ? '<span style="color: limegreen;">' + data.terminalCSQ + '</span>' : '<span style="color: red;">-<span>'}</div>
                  <div>更新时间：${data && data.ReadDate != null ? '<span style="color: limegreen;">' + data.ReadDate + '</span>' : '<span style="color: red;">-<span>'}</div>
                </div>`,
        });
        marker.setPopup(popup)

        // marker.on('click', (e) => {
        //   e.preventDefault()
        //   e.stopPropagation()
        //   this.examineTerminalMarkerLayer.getMarkers().forEach(m => m.closePopup())
        //   this.dyhTerminalMarkerLayer.getMarkers().forEach(m => m.closePopup())
        //   marker.openPopup()
        // })

        marker.on('mouseover', (e) => {
          marker.openPopup()
        })

        marker.on('mouseout', (e) => {
          marker.closePopup()
        })

        if (t.hookType === 1) {
          this.examineTerminalMarkerLayer.addMarker(marker);
        } else {
          this.dyhTerminalMarkerLayer.addMarker(marker);
        }
      })
      this.mapScene.addMarkerLayer(this.examineTerminalMarkerLayer);
      this.mapScene.addMarkerLayer(this.dyhTerminalMarkerLayer);
      if (!this.examineTerminalMarkerVisible) {
        this.examineTerminalMarkerLayer.hide()
      }
      if (!this.dyhTerminalMarkerVisible) {
        this.dyhTerminalMarkerLayer.hide()
      }
    },
    addPolygonLayer(scene, coords, color, id, name, rate, zIndex, zoom, isDma = false) {
      const that = this
      const source = {
        type: 'FeatureCollection',
        features: [
          {
            type: 'Feature',
            properties: {
              name: name,
              rate: '产销差率：' + rate + '%'
            },
            geometry: {
              type: 'Polygon',
              coordinates: coords,
            },
          },
        ],
      }

      const layerName = (isDma ? 'polygon-dma-' : 'polygon-dfq-') + id
      // 平面
      const layer = new PolygonLayer({name: layerName, zIndex: zIndex}).source(source)

      // 边界
      const lineLayerName = (isDma ? 'line-dma-' : 'line-dfq-') + id
      const lineLayer = new LineLayer({
        name: lineLayerName,
        zIndex: zIndex + 1
      }).source(source).color('#1890ff')

      if (isDma) {
        layer.color(color).style({
          opacity: 0.9,
        });
        // DMA 边界
        lineLayer.size(0.5)
      } else {
        layer.style({
          opacity: 0,
        });

        lineLayer.size(1.5)
      }

      scene.addLayer(lineLayer);

      layer.on('click', e => {
        // const popup = new Popup({
        //   offsets: [0, 0],
        //   closeButton: false,
        //   closeOnClick: true,
        // }).setLnglat(e.lngLat).setHTML(`<span>${e.feature.properties.name}</span><br/><span>产销差率: ${e.feature.properties.rate}%</span>`);
        // scene.addPopup(popup);
        that.handlePolygonLayerClick(scene, coords, id, name, rate, zoom, layer.coordCenter, isDma)
      });

      this.polygonLayers.push(layer)
      this.polygonLayers.push(lineLayer)

      scene.addLayer(layer)
    },
    resetLineLayerColorAndSize() {
      this.mapScene.getLayers().forEach(layer => {
        if (layer.name.startsWith('line-dma-')) {
          layer.color('#1890ff')
          layer.size(0.5)
        } else if (layer.name.startsWith('line-dfq-')) {
          layer.color('#1890ff')
          layer.size(1.5)
        }
      })
    },
    handlePolygonLayerClick(scene, coords, id, name, rate, zoom, coordCenter, isDma) {
      const that = this
      if (that.currentClickLayers.length) {
        that.currentClickLayers.forEach(layer => {
          scene.removeLayer(layer)
        })
        that.currentClickLayers = []
      }

      const dataSource = {
        type: 'FeatureCollection',
        features: [
          {
            type: 'Feature',
            properties: {
              name: name,
              rate: '产销差率：' + rate + '%'
            },
            geometry: {
              type: 'Polygon',
              coordinates: coords,
            },
          },
        ],
      };

      // 分区文本标记
      const textLayer1 = new PolygonLayer({zIndex: 5001})
        .source(dataSource)
        .color('red')
        .shape('name', 'text')
        .size(16)
        .style({
          textAnchor: 'center', // 文本相对锚点的位置 center|left|right|top|bottom|top-left
          textOffset: [0, 0], // 文本相对锚点的偏移量 [水平, 垂直]
          spacing: 2, // 字符间距
          padding: [1, 1], // 文本包围盒 padding [水平，垂直]，影响碰撞检测结果，避免相邻文本靠的太近
          // stroke: '#ffffff', // 描边颜色
          // strokeWidth: 0.3, // 描边宽度
          strokeOpacity: 1.0,
          fontWeight: 800
        });
      scene.addLayer(textLayer1);
      that.currentClickLayers.push(textLayer1)

      const textLayer2 = new PolygonLayer({zIndex: 5002})
        .source(dataSource)
        .color('red')
        .shape('rate', 'text')
        .size(16)
        .style({
          textAnchor: 'center', // 文本相对锚点的位置 center|left|right|top|bottom|top-left
          textOffset: [0, -25], // 文本相对锚点的偏移量 [水平, 垂直]
          spacing: 2, // 字符间距
          padding: [1, 1], // 文本包围盒 padding [水平，垂直]，影响碰撞检测结果，避免相邻文本靠的太近
          // stroke: '#ffffff', // 描边颜色
          // strokeWidth: 0.3, // 描边宽度
          strokeOpacity: 1.0,
          fontWeight: 800
        });
      scene.addLayer(textLayer2);
      that.currentClickLayers.push(textLayer2)

      that.resetLineLayerColorAndSize()

      const layer = this.mapScene.getLayerByName((isDma ? 'line-dma-' : 'line-dfq-') + id)
      layer.color('#ed368a').size(2)
      that.mapScene.render();

      scene.setZoomAndCenter(zoom, coordCenter)
    },
    drawDfqToMap() {
      if (this.dfqZoneData.length) {
        const that = this
        let zIndex = 1000
        let zoomLevel = 14
        this.dfqZoneData.forEach(dfq => {
          if (dfq.areaPoint) {
            if (dfq.zoom < zoomLevel) {
              zoomLevel = dfq.zoom - 1
            }
            that.zoomAndCenterMap(dfq)
            const coordinates = []
            coordinates.push(JSON.parse(dfq.areaPoint))
            const target = this.dfqKpiData.filter(item => item.id === dfq.areaID)
            let rate = 0
            if (target && target.length) {
              rate = target[0].rate
            }
            const color = this.getKpiRateColor(rate)
            this.addPolygonLayer(that.mapScene, coordinates, color, dfq.areaID, dfq.areaName, rate, zIndex, dfq.zoom, false)
            zIndex += 1
          }
        })
      }
    },
    drawDmaToMap() {
      if (this.dmaZoneData.length) {
        const that = this
        let zIndex = 2000
        this.dmaZoneData.forEach(dma => {
          if (dma.areaPoint) {
            that.zoomAndCenterMap(dma)
            const coordinates = []
            coordinates.push(JSON.parse(dma.areaPoint))
            const target = this.dmaKpiData.filter(item => item.id === dma.areaID)
            let rate = 0
            if (target && target.length) {
              rate = target[0].rate
            }
            const color = this.getKpiRateColor(rate)
            this.addPolygonLayer(that.mapScene, coordinates, color, dma.areaID, dma.areaName, rate, zIndex, dma.zoom, true)
            zIndex += 1
          }
        })
      }
    },
    zoomAndCenterMap(zone) {
      if (zone.areaPoint && !this.mapCenterFocused) {
        const coords = []
        coords.push(JSON.parse(zone.areaPoint))
        const turfPolygon = turf.polygon(coords);
        const centroid = turf.centroid(turfPolygon);
        const centerPoint = centroid.geometry.coordinates
        // this.mapScene.setZoomAndCenter(zone.zoom, [centerPoint[0], centerPoint[1]])
        this.mapScene.setCenter([centerPoint[0], centerPoint[1]])
        this.mapCenterFocused = true
      }
    },
    drawPipeNetwork() {
      // if (this.$store.getters.deptName.indexOf('增城自来水') !== -1) {
      //   const url1 = 'http://139.9.155.246:8088/geoserver/wms?SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&FORMAT=image%2Fpng&TRANSPARENT=true&STYLES&LAYERS=zengcheng:zhucun2_pipe&exceptions=application%2Fvnd.ogc.se_inimage&SRS=EPSG%3A4326&WIDTH=521&HEIGHT=768&BBOX={bbox}'
      //   this.pipeNetworkLayers.push(drawWmsLayer(this.mapScene, url1))
      //   const url2 = 'http://139.9.155.246:8088/geoserver/wms?SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&FORMAT=image%2Fpng&TRANSPARENT=true&STYLES&LAYERS=zengcheng:ningxi2_pipe&exceptions=application%2Fvnd.ogc.se_inimage&SRS=EPSG%3A4326&WIDTH=521&HEIGHT=768&BBOX={bbox}'
      //   this.pipeNetworkLayers.push(drawWmsLayer(this.mapScene, url2))
      // }
      const query = {}
      listGisLayer(query).then(res1 => {
        res1.rows.forEach(item => {
          if (item.layerType === 0 && item.layerName !== '节点') {
            // 管点
            listGisPoint({layerId: item.id}).then(res => {
              if (res.rows && res.rows.length) {
                const pointLayer = new PointLayer({
                  name: 'pointLayer-' + item.id,
                  zIndex: 1000
                }).source(res.rows, {
                  parser: {
                    type: 'json',
                    x: 'x',
                    y: 'y',
                  }
                }).shape('scode', scode => {
                  if (scode === '2') {
                    return 'shuichang'
                  } else if (scode === '4') {
                    return 'xiaofangshuan'
                  } else if (scode === '7') {
                    return 'famen'
                  }
                  return 'lianjiedian'
                }).size('scode', scode => {
                  if (scode === '1') {
                    return 10
                  }
                  return 15
                }).select({
                  color: '#ad7a10'
                })

                this.mapPointLayerList.push(pointLayer)
                this.mapScene.addLayer(pointLayer)

                if (item.layerName !== '节点') {
                  const imageLayerText = new PointLayer()
                    .source(res.rows, {
                      parser: {
                        type: 'json',
                        x: 'x',
                        y: 'y',
                      }
                    })
                    .shape('feature', 'text')
                    .color('#1359e5')
                    .size(16)
                    .style({
                      textOffset: [0, 25],
                      fontWeight: 800
                    })
                  this.mapPointLayerList.push(imageLayerText)
                  this.mapScene.addLayer(imageLayerText)
                }
              }
            })
          } else if (item.layerType === 1) {
            // 管线
            listGisLine({layerId: item.id}).then(res2 => {
              if (res2.rows && res2.rows.length) {
                res2.rows.forEach(item => {
                  // 将坐标从字符串转换为数组
                  item.coordinates = JSON.parse(item.coordinates)
                })

                const lineLayer = new LineLayer({
                  name: 'lineLayer-' + item.id,
                  zIndex: 100
                }).source(res2.rows, {
                  parser: {
                    type: 'json',
                    coordinates: 'coordinates'
                  }
                }).shape('line')
                  .size(1.5)
                  .color('red',)
                  .select({color: '#00F'});

                this.mapLineLayerList.push(lineLayer)
                this.mapScene.addLayer(lineLayer)
              }
            })
          }
        })
      })
    }
  },
  created() {
    this.screenHeight = document.body.clientHeight
  },
  computed: {
    moment() {
      return moment
    },
    getMapZoom() {
      if (this.$store.getters.deptName.indexOf('增城自来水') !== -1) {
        return 12
      }
      return 14
    },
    getTableHeight() {
      return this.screenHeight - 699
    },
    getMapHeight() {
      const h = this.screenHeight - 262
      return {height: h + 'px'}
    }
  },
  mounted() {
    this.initChart()
    this.loadOverviewData()
    this.loadDfqKpiData()
    this.loadDMAKpiData()
    this.loadMonitorTerminals()
  }
};
</script>

<style scoped lang="scss">
.box1 {
  height: 110px;
  border: 1px solid #E3E3E3;

  .top {
    width: 100%;
    height: 55%;
    text-align: center;
    padding: 14px 8px;
    font-size: 24px;
  }

  .value {
    font-weight: bold;
    font-size: 26px;
  }

  .rate {
    font-size: 18px;
  }

  .bottom {
    width: 100%;
    height: 45%;
    text-align: center;
    color: #FFFFFF;
    font-size: 16px;
    font-weight: bold;
    background-color: #1890ff;
    padding: 10px;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
}

.box2 {
  height: 715px;
  border: 1px solid #E3E3E3;
}

.home {
  blockquote {
    padding: 10px 20px;
    margin: 0 0 20px;
    font-size: 17.5px;
    border-left: 5px solid #eee;
  }

  hr {
    margin-top: 20px;
    margin-bottom: 20px;
    border: 0;
    border-top: 1px solid #eee;
  }

  .col-item {
    margin-bottom: 20px;
  }

  ul {
    padding: 0;
    margin: 0;
  }

  font-family: "open sans", "Helvetica Neue", Helvetica, Arial, sans-serif;
  font-size: 13px;
  color: #676a6c;
  overflow-x: hidden;

  ul {
    list-style-type: none;
  }

  h4 {
    margin-top: 0px;
  }

  h2 {
    margin-top: 10px;
    font-size: 26px;
    font-weight: 100;
  }

  p {
    margin-top: 10px;

    b {
      font-weight: 700;
    }
  }

  .update-log {
    ol {
      display: block;
      list-style-type: decimal;
      margin-block-start: 1em;
      margin-block-end: 1em;
      margin-inline-start: 0;
      margin-inline-end: 0;
      padding-inline-start: 40px;
    }
  }
}

::v-deep .l7-popup .l7-popup-content {
  position: relative;
  padding: 16px;
  font-size: 14px;
  color: #FFFFFF;
  background: #5e72af;
  border-radius: 3px;
  -webkit-box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

::v-deep .l7-popup-anchor-bottom .l7-popup-tip {
  -webkit-align-self: center;
  -ms-flex-item-align: center;
  align-self: center;
  border-top-color: #5e72af;
  border-bottom: none;
}
</style>

